package primary.primary0;

public class S0160相交链表 {
    public class Solution {
        /**
         * 99
         * a跑到头之后接着b跑，b跑到头之后接着a跑，总会相等的
         * 但是注意只能掉头一次，出现第二次的话，要跳出去，毕竟会有没有重合点的case
         */
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode tempA = headA;
            ListNode tempB = headB;
            boolean canContinueA = true;
            boolean canContinueB = true;
            while(tempA != tempB && tempA!=null && tempB!=null){
                // System.out.println("a" + tempA.val + "  b" + tempB.val);
                tempA = tempA.next;
                tempB = tempB.next;

                if(tempA == null && canContinueA){
                    tempA = headB;
                    canContinueA = false;
                }
                if(tempB == null && canContinueB){
                    tempB = headA;
                    canContinueB = false;
                }
            }
            if(tempA == tempB){
                return tempA;
            }
            return null;
        }
    }

    /**
     * 答案
     * 哈哈，null == null 是true，所以直接调头就行，调一次，走到
     */
    public class Solution2 {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if (headA == null || headB == null) {
                return null;
            }
            ListNode pA = headA, pB = headB;
            while (pA != pB) {
                pA = pA == null ? headB : pA.next;
                pB = pB == null ? headA : pB.next;
            }
            return pA;
        }
    }

    public static void main(String[] args) {
        System.out.println(null == null);
    }

}
